﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AlertSystem.PluggableModules;
using AlertSystem.SendEms.WSEmsLog;
using AlertSystem.Business;
using Utils;

namespace AlertSystem.SendEms
{
    public class SendAlert : WorkingBaseSendAlert
    {
        #region Properties and field
        private sami_error_logdev ems_log = new WSEmsLog.sami_error_logdev();
        public string UserName { get { return GetConfig("UserName"); } set { SetConfig("UserName", value); } }
        public string Password { get { return GetConfig("Password"); } set { SetConfig("Password", value); } }
        public string AuthKey { get { return GetConfig("AuthKey"); } set { SetConfig("AuthKey", value); } }
        #endregion

        protected override void Send(Warning_Message msg, List<Warning_Account_Method> accountMethods)
        {
            try
            {
                Warning_Type warning_type = Warning_Type.GetByID(msg.WarningType, msg.WarningSystem);
                Warning_System warning_system = Warning_System.GetByID(msg.WarningSystem);
                string priority = warning_type == null ? "urgent" : warning_type.Priority;
                int severity = warning_type == null ? 0 : warning_type.Severity;
                string system = warning_system == null ? "" : warning_system.System_Id;       
                string assignedTo = string.Join(",", accountMethods.Select(p => p.Account_Config));
                string strxml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><records><record><priority>{0}</priority><error_content>{1}</error_content><assigned_to>{2}</assigned_to><system>{3}</system><severity>{4}</severity><created_on>{5}</created_on><summary>{6}</summary></record></records>",
                                           priority, msg.Message, assignedTo, system, severity, String.Format("{0:yyyy-MM-dd HH:mm:ss}", msg.Message_Time), msg.Message.Length > 255 ? msg.Message.Substring(0, 255) : msg.Message);
                string base64encode = Convert.ToBase64String(Encoding.UTF8.GetBytes(strxml));
                string checksum = strxml.ToMD5Hash();
                returnRecord record = ems_log.insertErrorLog(base64encode, checksum, UserName, Password, AuthKey);
            }
            catch (Exception ex)
            {
                Warning_Log.InsertLog(ex);
            }
        }
    }
}
